#!/bin/bash -x

kata_coco_top_dir="$HOME/workspace/CoCo/"

kata_containers_repo_url="https://gitee.com/hanliyang-kata-coco/kata-containers.git"
kata_containers_repo_branch="3.13.0-hygon-arch-sig"
kata_containers_repo_dir="${kata_coco_top_dir}/kata-containers"

if [ ! -e ${kata_containers_repo_dir} ]; then
  git clone ${kata_containers_repo_url} \
    -b ${kata_containers_repo_branch} \
    ${kata_containers_repo_dir}
fi

# check and install yq if not exist
echo "[Check and Install yq]"
command yq > /dev/null
if [ $? -ne 0 ]; then
  DEBUG="y" ${kata_containers_repo_dir}/ci/install_yq.sh
  echo 'export PATH=$PATH:$HOME/go/bin/' >> $HOME/.bashrc
  source $HOME/.bashrc
fi

# install oras
install_pause_builder_deps () {
  echo "[Install oras]"
  rm -rf /tmp/oras.*
  oras_url=https://github.com/oras-project/oras/releases/download/v1.0.0/oras_1.0.0_linux_amd64.tar.gz
  oras_src_tarball=/dev/shm/oras_1.0.0_linux_amd64.tar.gz
  oras_install_dir=$(mktemp -d -t oras.XXXXXXXX)
  if [ ! -e ${oras_src_tarball} ]; then
    wget -O ${oras_src_tarball} ${oras_url}
  fi
  sudo tar -zxvf ${oras_src_tarball} -C ${oras_install_dir}
  sudo rm /usr/bin/oras
  sudo ln -s ${oras_install_dir}/oras /usr/bin/oras
}

install_pause_builder_deps

patch_proxy_for_pause_builder () {
  if [ "X${http_proxy}" != "X" ]; then
    echo "[Update proxy for pause builder]"
    pushd ${kata_containers_repo_dir}
    git checkout .
    curl -sSL https://gitee.com/hanliyang-kata-coco/deployment/raw/master/how-to-build/assets/diff.build-pause-image-rootfs | git apply
    build_script=$(realpath tools/packaging/static-build/pause-image/build-static-pause-image.sh)
    sed -i "s!\${your_proxy}!${http_proxy}!g" ${build_script}
    builder_dockerfile=$(realpath tools/packaging/static-build/pause-image/Dockerfile)
    sed -i "/FROM ubuntu:22.04/a RUN echo 'Acquire::http::Proxy \"${http_proxy}\";\\\\nAcquire::https::Proxy \"${https_proxy}\";' > /etc/apt/apt.conf.d/10proxy" ${builder_dockerfile}
    sed -i "/ENV DEBIAN_FRONTEND=noninteractive/i RUN cat /etc/apt/apt.conf.d/10proxy" ${builder_dockerfile}
    popd # ${kata_containers_repo_dir}
  fi
}

patch_proxy_for_pause_builder

pause_builder_dir="$(realpath ${kata_containers_repo_dir}/tools/packaging/kata-deploy/local-build)"

build_pause_image_rootfs () {
  echo "[Build pause image rootfs]"
  pushd ${pause_builder_dir}
  DOCKER_BUILDKIT=1 \
  BUILDKIT_PROGRESS=plain \
  ./kata-deploy-binaries.sh --build=pause-image
  popd
}

build_pause_image_rootfs
